import { Button, DataGrid, LoadIndicator, Popup, SelectBox, TextBox, TreeView } from "devextreme-react";
// import "./index.less"
import { useModel } from "umi";
import { intl } from "@/utils";
// import DevTreeRight from "./DevTree/index";
import SetReclassiFiedItem from "./SetReclassiFiedItem";
// import { getSubjectList, getSubjectType } from "@/pages/ReportFinancial/service";
// import { AdjustingEntryKMMapSave, getKMMapDataList, updateMap, } from "./service";
import { DevToolBar, CpasIcon, DevGrid, LayoutB, SortableDevGrid, DevPopup, DevTree } from '~/public/cpas-ui';
import React, { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import AntTabs, { HocVerticalLeftStyleTab, HocVerticalRightStyleTab } from '~/public/cpas-ui/components-ui/ant-components/AntTab';
import { postFetchData } from "../service";
import notify from "devextreme/ui/notify";
import * as ReactDOMClient from 'react-dom/client';
// import { DevTree, LayoutB, DevPopup } from '~/public/cpas-ui';

const SetClassiFicationAuto: React.FC<any> = React.forwardRef((props: any, ref) => {
    const { initialState } = useModel('@@initialState');
    const { dbname } = initialState?.curPart as API.CurPart;
    const { username } = initialState?.curUser as API.CurUser;
    const { width, height, isQC, DataId,refresh } = props

    const Divstyle: React.CSSProperties = { display: 'flex', alignItems: "center", justifyContent: "center", marginRight: '10px' };
    const [openVisible111111, setOpenVisible111111] = useState<boolean>(false);

    const diaParams = useRef<any>();
    const displayName = useRef<any>();
    const devGridRef = useRef<any>();
    const DeletePopupRef = useRef<any>();
    const SetReclassiFiedItemRef = useRef<any>();
    const subjectlist= useRef<any>();

    // const [state,setState] = useState<boolean>(false);
    const [visible, setVisible] = useState<boolean>(false);
    const isChange = useRef<boolean>(false);

    const [data, SetData] = useState<any[]>([])
    const [AccountTreeList, setAccountList] = useState<any[]>([]) // 科目
    // const [displayName, setDisplayName] = useState<string>('')
    const [AccountFilterData, setAccountFilterData] = useState<any[]>([]) // 试算项目

    const ficationTabsData = [{ code: "0", type: "全部" }, { code: "1", type: "资产" }, { code: "2", type: "负债" }, { code: "3", type: "利润" }]

    const subjectsTabsData = [{ code: "0", type: "全部" },
    { code: "1", type: "资产" },
    { code: "2", type: "负债" }, { code: "3", type: "权益" }, { code: "4", type: "成本" }, { code: "5", type: "损益" }]




    // 获取树表格数据
    const getSubjectListDatas = async (params: { DataId: any, zhTZQJ: string, type?: string }) => {
        const { DataId, zhTZQJ, type } = params;
        let postData: any = {};
        if (type === '全部') {
            postData = {
                dbName: dbname,
                tableName: `${DataId}_试算平衡`,
                zhTZQJ: zhTZQJ,

            }
        } else {
            postData = {
                dbName: dbname,
                tableName: `${DataId}_试算平衡`,
                zhTZQJ: zhTZQJ,
                type: type,
            }

        }
        const [res] = await Promise.all([
            postFetchData('designCell.TbItemName', postData)
        ])
        // debugger
        if (res.ok) {
            console.log(res.data)
            setAccountFilterData(res.data);
        }

    };

    /**
     *  获取科目类型数据
     * @param params 
     */
    const getSubjectTypeData = async (params: { DataId: any; }) => {
        const { DataId } = params
        const [res] = await Promise.all([
            postFetchData('account.subject.getDataList', {
                dbname: dbname,
                isHasFZZ: false,
                Data_ID: DataId
            })])

        if (res.ok) {
            subjectlist.current = res.data
            setAccountList(res.data)
        }
    }

    // 每次点击触发接口事件 进行右侧树渲染和列表的过滤数据展示
    useImperativeHandle(ref, () => ({
        show: async (params: any) => {
            debugger
            setOpenVisible111111(true);
            diaParams.current = params;
            setVisible(true);
            
            await getSubjectTypeData(params);
            await getSubjectListDatas(params);
            setOpenVisible111111(false);
            SetData(diaParams.current.leftItemList)

        },
    }))

    // 点击关闭按钮逻辑
    const onHiding = () => {
        setVisible(false);
        displayName.current = '';
        console.log("刷新表格")
        if (isChange.current) {
            refresh()
        }
    

    }



    const columns = [
        {
            dataField: "DG_NAME",
            dataType: "string",
            caption: "底稿表页名称 *",
            width: 180,
            // alignment: "left",
            allowEditing: false,
            allowUpdating: false,
        },
        {
            dataField: "itemName",
            dataType: "string",
            caption: "试算项目名称 *",
            width: 150,
            // alignment: "left",
            allowEditing: false,
            allowUpdating: false,
            validationRules: [
                
            ]
        },

        {
            dataField: "KMMC",
            dataType: "string",
            caption: "科目名称",
            width: 130,
            // alignment: "left",
            allowEditing: true,
            allowUpdating: true,
            cellTemplate: (cell: any,data:any) => {
                // console.log(data.key.KMMC, data);
                return  ReactDOMClient.createRoot(cell).render( <div style={{ display: "flex", justifyContent: "space-between" }}>
                    <span style={{ marginLeft: "10%" }}>{data.displayValue}</span>
                    <span style={{ marginRight: "10px" }}>
                        {/* 点击 清空 */}
                        <CpasIcon type='icon-chexiao' onClick={async () => {
                            DeletePopupRef.current.show({
                                title: "提示",
                                okCallback: async () => {
                                    devGridRef.current.instance.cellValue(displayName.current.rowIndex, 'KMMC', "");
                                    devGridRef.current.instance.saveEditData();
                                    // devGridRef.current.instance.cellValue(displayName.current.rowIndex, 'CFLNo', "");
                                }
                            });
                        }} />
                    </span>
                </div>)
            }
        },
       
    ]
    // 右侧 切换方法
    /**
     * 获取项目
     * @param r 
     * @returns 
     */
    const getSubjectListData = async (r: string) => {
        console.log(r)
        await getSubjectListDatas({ type: r, DataId: DataId, zhTZQJ: isQC })
    };
    /**
     * 项目点击
     */
    const AccountTabsClick = useCallback(async (r: any,) => {
        // setTbsStates(r)
        console.log(r)
        ficationTabsData.map(async (item: any) => {
            if (r === item.code) {
                await getSubjectListData(item.type);
            }
        })
    }, [ficationTabsData])

    /**
     * 
     * @param r 科目点击
     */
    const subjectTabsClick = (async (r: any,) => {
        console.log(r)
        subjectsTabsData.map(async (item: any) => {
            if (r === item.code) {
                // debugger
                if (r === '0') {
                    
                    setAccountList(  subjectlist.current )
                } else {
                    setAccountList(  subjectlist.current.filter((it: any) => {
                        return it.KMLX && it.KMLX.includes(item.type)
                    }) )
                }
              
            }
        })
    })

    function leftContainer() {
        return (
            <div style={{ width: '98%', height: 'calc(100vh - 210px)', }}>


                <DataGrid
                    className="grid_Style"
                    ref={devGridRef}
                    hoverStateEnabled={true}
                    focusedRowEnabled={true}
                    dataSource={data}
                    width='100%'
                    height='100%'
                    keyExpr="DG_NAME"
                    columns={columns as []}
                    showBorders={true}
                    showRowLines={true}
                    showColumnLines={true}
                    allowColumnResizing={true}
                    columnResizingMode="widget"
                    headerFilter={{ visible: false }}
                    filterPanel={{ visible: false }}
                    filterRow={{ visible: false }}
                    paging={{
                        enabled: false
                    }}
                    editing={{
                        allowAdding: false,
                        allowUpdating: true,
                        allowDeleting: false,
                        mode: "cell"
                    }}
                    selection={{
                        allowSelectAll: false,
                    }}
                    onCellClick={(res: any) => {
                        console.log(res, 'res.rowIndex----');
                        displayName.current = res
                    }}
                    
                />


            </div>
        )
    }
    // const refreshSubject = (r: boolean) => {
    //     if (r) {
    //         getSubjectTypeData(diaParams.current);
    //         getSubjectListDatas(diaParams.current);
    //     }
    // }

    /**
     * 试算项目
     * @param e 
     * @returns 
     */
    const onItemClick = async (e: any) => {
        console.log(e, 'e--------------');
        if (displayName.current !== undefined) {
            if (displayName.current.rowIndex >= 0) {
                // if(e.level === 66 )
                
                devGridRef.current.instance.cellValue(displayName.current.rowIndex, 'itemName', e.itemData.itemName);
                await devGridRef.current.instance.saveEditData();
                // devGridRef.current.instance.cellValue(displayName.current.rowIndex, 'itemName',  e.code);

            }
            return {};
        } else {
            notify( "请先选择左侧试算项目","warning",2000);
           
        }
        return '';
    }

    /**
     *  科目
     * @param e 
     * 
     * 
     *  */
    const onSubjustClick = async (e: any) => {
        console.log(e, 'e--------------');
        // debugger
        if (displayName.current !== '') {
            if (displayName.current.rowIndex >= 0) {
                // if(e.level === 66 )
                // debugger
                devGridRef.current.instance.cellValue(displayName.current.rowIndex, 'KMMC', e.itemData.displayName);
                devGridRef.current.instance.saveEditData();
                // devGridRef.current.instance.cellValue(displayName.current.rowIndex, 'CFLNo', e.level === 66 ? e.YSKMBH : e.code);

            }
            return {};
        } else {
            notify( "请先选择左侧科目","warning",2000);
        }
        // return '';
    }

    function rightContainer() {
        return (
// onChange={getSubjectListData} 
            <AntTabs style={{ height: '100%', marginLeft: "10px" }}  >
                <AntTabs.TabPane tab="试算列表" key="1" >

                    <AntTabs
                        // activeKey={"0"}
                        tabPosition={"right"}
                        className="changeTasHeightBox"
                        onChange={AccountTabsClick}
                    >
                        {
                            ficationTabsData.map((item: any) => {
                                return (<AntTabs.TabPane
                                    tab={item.type}
                                    key={item.code}
                                >
                                    <TreeView
                                        id="treeview"
                                        width={'100%'}
                                        height={'calc(100vh - 350px)'}
                                        dataStructure="plain"
                                        // ref={treeViewRef}
                                        // dataSource={AccountFilterData}
                                        items={AccountFilterData}
                                        searchMode="contains"
                                        displayExpr="itemName"

                                        // keyExpr="itemName"
                                        // selectByClick={true}
                                        searchEnabled={true}
                                        
                                        virtualModeEnabled={true}
                                        
                                        onItemClick={onItemClick}
                                    // onSelectionChanged={onItemClick}
                                    />
                                </AntTabs.TabPane>

                                )
                            })

                        }
                    </AntTabs>


                </AntTabs.TabPane>
                <AntTabs.TabPane tab="科目列表" key="2">

                    <AntTabs
                        // activeKey={"0"}
                        tabPosition={"right"}
                        className="changeTasHeightBox"
                        onChange={subjectTabsClick}
                    >
                        {
                            subjectsTabsData.map((item: any) => {
                                return <AntTabs.TabPane
                                    tab={item.type}
                                    key={item.code}
                                >
                                  
                                    <TreeView
                                        id="treeViewTest"
                                        height={'calc(100vh - 350px)'}
                                        // ref={devTreeRef}
                                        selectionMode='single'
                                        selectByClick={true}
                                        items={AccountTreeList}
                                        dataStructure="plain"
                                        searchMode="contains"
                                        displayExpr='displayName'
                                        parentIdExpr='PID'
                                        keyExpr='ID'
                                        rootValue='0'
                                        searchEnabled={true}
                                        onItemClick={onSubjustClick}
                                    // onItemContextMenu={treeViewItemContextMenu}
                                    />
                                </AntTabs.TabPane>
                            })
                        }
                    </AntTabs>
                </AntTabs.TabPane>
            </AntTabs>
        )
    }
    const OK = async () => {
      
      
      let dd =devGridRef.current?.instance.getDataSource()._items;
      diaParams.current.isok(dd)
      setVisible(false);
    }
    return (
        <div >
            <Popup
                shadingColor='rgba(0, 0, 0, 0)'
                shading={true}
                width={'90vw'}
                height="85%"
                ref={ref}
                dragOutsideBoundary={true}
                resizeEnabled={true}
                visible={visible}
                animation={{ duration: 3 }}
                title='设置批量对应关系'
                // minWidth={500}
                // minHeight={300}
                {...props}
                // {...size}
                onHiding={onHiding}
                // onResizeEnd={(e) => {
                //     setSize({ width: e.width, height: e.height });
                // }}
                toolbarItems={[
                 
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.cancel', '关闭'),
                            onClick: () => {
                                setVisible(false);
                                displayName.current = '';
                            }
                        },
                    },
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.ok', '确定'),
                            type: 'default',
                            onClick: () => OK()
                        },
                    },
                ]}
            >

                <div  >
                    {openVisible111111 && <div style={{
                        position: 'absolute', width: '100%', height: '100%', display: 'flex', alignItems: "center", justifyContent: "center",
                        opacity: 0.5, zIndex: "99999", background: "#ddd"
                    }}>
                        <LoadIndicator id="medium-indicator" height={50} width={50} />
                    </div>}
                    <LayoutB
                        rowSize={["10%", "70%", "80%"]}
                        leftSlot={leftContainer()}
                        rightSlot={rightContainer()}
                    />
                </div >
            </Popup >
            {/* <SetReclassiFiedItem ref={SetReclassiFiedItemRef} DataId={diaParams.current?.DataId} width={600} height={500} refresh={()=>refresh()} closed={() =>onHiding() }/> */}
            <DevPopup.Default ref={DeletePopupRef} width={80} height={200} >
                {() => {
                    return <span>确定要执行此操作吗？</span>
                }}
            </DevPopup.Default>
        </div >
    )
});

export default React.memo(SetClassiFicationAuto); 